package com.wx.controller;

import com.wx.service.QRCodeService;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.wx.common.utils.MD5Utils;
import com.wx.pojo.QRCode;
import com.wx.pojo.User;
import com.wx.service.UserService;
import com.wx.utils.CreateQRCode;
import com.wx.utils.FastDFSClient;
/**
 * 用户注册
 * @author gzcadmin
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private QRCodeService QRCodeService;
	/**
	 * 注册信息登录信息
	 * errno：0:代表注册成功   1：代表注册失败  2：代表手机号已存在
	 * 
	 * 
	 */
	@RequestMapping(value ="/register" ,method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> register(HttpServletRequest request,
			HttpServletResponse response ){

//		response.setContentType("text/html;charset=utf-8");          
//        /* 设置响应头允许ajax跨域访问 */  
//        response.setHeader("Access-Control-Allow-Origin", "*");  
//        /* 星号表示所有的异域请求都可以接受， */  
//        response.setHeader("Access-Control-Allow-Methods", "GET,POST");  
		
		Map<String,Object> map=new HashMap<String,Object>();
		
		//1.获取注册参数
		String phone=request.getParameter("phone");
		String password=MD5Utils.md5(request.getParameter("password"));
		String nickName=request.getParameter("nickName");
		String realname=request.getParameter("realname");
		
		
		
		
		//2.存入对象user中
		User user=new User();
		user.setPhone(phone);
		user.setPassword(password);
		user.setNickName(nickName);
		user.setRealname(realname);
		//转换日期
		java.util.Date date = new java.util.Date();          // 获取一个Date对象
        Timestamp timeStamp = new Timestamp(date.getTime()); 
        user.setRegist_time(timeStamp);
		
        List<User> userList=userService.findUserByPhone(user.getPhone());
        if(!userList.isEmpty() || userList.size()!=0) {
        	map.put("errno", 2);
        	map.put("errMsg", "手机号已存在");
        	return map;
        }
		userService.insertUser(user);
		//判断用户id是否存在，若存在表示注册成功
		if(user.getId()!=null) {
			User registerUser=userService.findUserById(user.getId());
			try {
				//生成二维码图片，传入二维码所需要的字符信息
				String qr_path=CreateQRCode.createqrCode(user.getId());
				//获取图片上传的配置文件路径
				 String confPath= ResourceBundle.getBundle("properties/FastDFSConfPath").getString("path");
			     FastDFSClient fastDFSClient = new FastDFSClient(confPath);
			     //获取二维码图片上传图片服务器的路径
				String qr_url=fastDFSClient.uploadFile(qr_path,"jpg");
				System.out.println(qr_url);
				//删除产生在本地的二维码图片
				CreateQRCode.removeQRimage(qr_path);
				QRCode qrCode=new QRCode();
				qrCode.setUserId(user.getId());
				qrCode.setQrUrl(qr_url);
				//存入数据库
				QRCodeService.addQRCode(qrCode);
				//判断是否成功存入数据库
				if(qrCode.getQrId()!=null) {
					System.out.println("registerUser: "+registerUser);
					map.put("errno", 0);
					request.getSession().setAttribute("userInfo", registerUser);
					map.put("userInfo",registerUser);
				}else {
					map.put("errno", 2);
					map.put("errmsg", "生成二维码失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}else {
			map.put("errno", 1);
			map.put("errMsg", "注册失败");
		}
		
		return map;
	}
	
	/**
	 * 登录
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> login(HttpServletRequest request,
			HttpServletResponse response ){

		Map<String,Object> map=new HashMap<String,Object>();
		
		//1.获取登录参数
		String phone=request.getParameter("phone");
		String password=MD5Utils.md5(request.getParameter("password"));
		
		//2.存入对象user中
		User user=new User();
		user.setPhone(phone);
		user.setPassword(password);
		System.out.println(phone+"   "+password);
		User loginUser=userService.findUserByphoneAndPassword(user);
		
		if(loginUser!=null) {
			map.put("errno", 0);
			request.getSession().setAttribute("userInfo", loginUser);
			map.put("userInfo", loginUser);
		}else {
			map.put("errno", 1);
			map.put("errMsg", "登录失败");
		}
		return map;
	}
	
	/**
	 * 退出登录
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/loginOut",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> loginOut(HttpServletRequest request){
		Map<String,Object> map=new HashMap<String,Object>();
		request.getSession().removeAttribute("userInfo");
		map.put("errno", 0);//0：代表成功推出
		return map;
	}
	/**
	 * 修改用户信息
	 * @param userId
	 * @param phone
	 * @param nickName
	 * @param realName
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/alterUser",method=RequestMethod.GET)
	@ResponseBody
	public Map<String,Object>alterUser(
			@RequestParam("userId")String userId,
			@RequestParam("phone")String phone,
			@RequestParam("nickName")String nickName,
			@RequestParam("realName")String realName) throws UnsupportedEncodingException{
		Map<String,Object> modelMap=new HashMap<String,Object>();
//		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); 
//		request.setCharacterEncoding("UTF-8");
		nickName =new String(nickName.getBytes("ISO8859-1"),"utf-8");
		realName =new String(realName.getBytes("ISO8859-1"),"utf-8");
		User user = new User();
		user.setId(userId);
		System.out.println("userId: "+userId);
		user.setPhone(phone);
		user.setNickName(nickName);
		user.setRealname(realName);
		userService.alterUser(user);
		User alterUser=userService.findUserById(userId);
		modelMap.put("errno", 0);//更新成功
		modelMap.put("alterUser",alterUser);
		return modelMap;
	}
	/**
	 * 修改密码
	 * @param phone
	 * @param password
	 * @return
	 */
	@RequestMapping(value="/alterPassworder",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object>alterUserPassworder(
			@RequestParam("phone")String phone,
			@RequestParam("newPassword")String password){
		Map<String,Object> modelMap=new HashMap<String,Object>();
		User user = new User();
		user.setPhone(phone);
		user.setPassword(MD5Utils.md5(password));
		userService.alterUserPasswordByPhone(user);
		modelMap.put("errno", 0);//修改密码成功
		return modelMap;
	}
	/**
	 * 通过用户id查询用户信息
	 * @param user_id
	 * @return
	 */
	@RequestMapping(value="/findUserById",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> findUserById(@RequestParam("user_id")String user_id){
		Map<String,Object> modelMap=new HashMap<String,Object>();
		User user=userService.findUserById(user_id);
		if(user!=null) {
			modelMap.put("errno", 0);
			modelMap.put("userName", user.getRealname());
			modelMap.put("phone", user.getPhone());
		}
		return modelMap;
	}
	
	
}
